package com.tem.system.service.impl;

import com.api.manage.pojo.content.CmsTypeBean;
import com.api.manage.pojo.system.SysRegionBean;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tem.system.entity.SysRegion;
import com.tem.system.mapper.SysRegionMapper;
import com.tem.system.service.ISysRegionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 区域 服务实现类
 * </p>
 *
 * @author 鸿源塔基
 * @since 2023-06-09
 */
@Service
public class SysRegionServiceImpl extends ServiceImpl<SysRegionMapper, SysRegion> implements ISysRegionService {
    public List<SysRegionBean> getTree(){
        QueryWrapper<SysRegion> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("sort");
        queryWrapper.eq("type",1);
        List<SysRegion> list = this.list(queryWrapper);
        if(list==null||list.size()<1)return null;
        List<SysRegionBean> beans = new ArrayList<>();
        SysRegionBean ctb = null;
        for (SysRegion c:list){
            ctb = new SysRegionBean();
            BeanUtils.copyProperties(c,ctb);
            beans.add(ctb);
            QueryWrapper<SysRegion> chlistsQW = new QueryWrapper<>();
            chlistsQW.likeRight("region_path",c.getRegionPath());
            chlistsQW.orderByDesc("sort");
            buildTree(ctb, toBean(this.baseMapper.selectList(chlistsQW)));
        }
        return beans;
    }
    public void buildTree(SysRegionBean parent,List<SysRegionBean> list){//获取字节的
        for(SysRegionBean b:list){
            if(b.getParentId().equals(parent.getSysRegionId())){
                parent.getChildren().add(b);//子节点
                buildTree(b,list);//递归继续找子节点
            }
        }
    }
    public List<SysRegionBean> toBean(List<SysRegion> list){
        List<SysRegionBean> beans = new ArrayList<>();
        if(list==null || list.size()<1)return beans;
        SysRegionBean ctb = null;
        for (SysRegion c:list) {
            ctb = new SysRegionBean();
            BeanUtils.copyProperties(c, ctb);
            beans.add(ctb);
        }
        return beans;
    }
}
